#include "RecvLine.h"


RecvLine::RecvLine(void)
{
	m_nConn = 0;
	m_nRecvByte = 0;
	m_nCopyByte = 0;
	m_bClosed = false;
	memset(m_cCopyBuf, 0, CustomBuf::SYNBUFSIZE + 1);
	memset(m_cRecvBuf, 0, CustomBuf::BIGBUF + 1);
}

RecvLine::RecvLine(SOCKET s)
{
	m_nConn = s;
	m_nRecvByte = 0;
	m_nCopyByte = 0;
	m_bClosed = false;
	memset(m_cCopyBuf, 0, CustomBuf::SYNBUFSIZE + 1);
	memset(m_cRecvBuf, 0, CustomBuf::BIGBUF + 1);
}


RecvLine::~RecvLine(void)
{
}

void RecvLine::CopyLine(void)
{
readmore:
	if (m_nRecvByte <= 0)
	{
		if(!Receive(m_nConn))
		{
			return;
		}
	}
	m_pcCopy = m_cCopyBuf;

	for (m_nCopyByte = 1; *m_pcRecv != '\n' && m_nRecvByte > m_nCopyByte; ++m_nCopyByte, ++m_pcRecv, ++m_pcCopy)
	{
		*m_pcCopy = *m_pcRecv;
	}
	*m_pcCopy = *m_pcRecv;
	m_nRecvByte -= m_nCopyByte;

	if (*m_pcRecv != '\n')
	{
		goto readmore;
	}

	++m_pcCopy, ++m_pcRecv;
	*m_pcCopy = 0;
}

bool RecvLine::Receive(SOCKET s)
{
	if ((m_nRecvByte = recv(s, m_cRecvBuf, CustomBuf::BIGBUF, 0)) <= 0)
	{
		closesocket(s);
		m_bClosed = true;
		return false;
	}
	m_pcRecv = m_cRecvBuf;
	m_pcRecvEnd = m_pcRecv + m_nRecvByte;
	return true;
}
